#ifndef DEVICECONTROLLER_H
#define DEVICECONTROLLER_H

#include <QObject>
#include <QThread>
#include <QMutex>
#include "types.h"
#include "enums.h"

class DeviceWorker;

class DeviceController : public QObject
{
    Q_OBJECT

public:
    static DeviceController* instance();
    static void destroyInstance();

    DeviceController(const DeviceController&) = delete;
    DeviceController& operator=(const DeviceController&) = delete;

    void initialize();

    // 网络连接管理
    Q_INVOKABLE void connectToDevice(const QString &host, quint16 port);
    Q_INVOKABLE void disconnectFromDevice();
    Q_INVOKABLE bool isConnected() const;

    // 统一的命令发送接口
    Q_INVOKABLE void sendCommand(DeviceProtocol::IPCCommand command,
                                 const QVariantMap &params = QVariantMap());

signals:
    // 状态信号 - 使用结构体而不是 QVariantMap
    void connected();
    void disconnected();
    void errorOccurred(const QString &error);
    void processParametersReceived(ProcessParams params);
    void commandResponseReceived(DeviceProtocol::IPCCommand command,
                                 bool success, const QString &message);
    void commandDataResponseReceived(DeviceProtocol::IPCCommand command,
                                     bool success, const QVariantMap &data);
     void queryDataReceived(DeviceProtocol::IPCCommand command, const QVariantMap &data); // 查询数据信号

    void initialized();

    // 内部信号（转发到工作线程）
    void initRequested();
    void connectRequested(const QString &host, quint16 port);
    void disconnectRequested();
    void commandRequested(DeviceProtocol::IPCCommand command,
                          const QVariantMap &params);

private:
    explicit DeviceController(QObject *parent = nullptr);
    ~DeviceController();

    static DeviceController* m_instance;
    static QMutex m_mutex;

    QThread m_workerThread;
    DeviceWorker *m_worker;
    bool m_initialized;
};

#endif // DEVICECONTROLLER_H
